let tbody = document.querySelector('table tbody')
let loading = document.querySelector('.loading')

function format(time) {
    let date = new Date(time)
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
}

const myAjax = function (options) {
    let method = options.method || 'GET'
    let url = options.url
    let data = options.data ? JSON.stringify(options.data) : JSON.stringify({})
    let xhr = new XMLHttpRequest()
    xhr.open(method, url)
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.send(data)
    xhr.responseType = 'json'
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                options.success(xhr.response)
            } else {
                options.error({
                    text: xhr.statusText,
                    status: xhr.status
                })
            }
        }
    }
}

const renderList = function () {
    loading.style.display = 'flex'
    myAjax({
        url: 'https://veihwwnelcwq.leanapp.cn/bmi',
        success: function (res) {
            loading.style.display = 'none'
            // get data
            const bmiData = res.data
            // const bmiData = []
            // render html
            tbody.innerHTML = ''
            if (bmiData.length === 0) {
                // empty
                tbody.insertAdjacentHTML('beforeend', `<tr><td colspan="6">暂无数据</td></tr>`)
            } else {
                for (let i = 0; i < bmiData.length; i++) {
                    tbody.insertAdjacentHTML('beforeend', `<tr>
                        <td>${i + 1}</td>
                        <td>${format(bmiData[i].createdAt)}</td>
                        <td>${bmiData[i].height}</td>
                        <td>${bmiData[i].weight}</td>
                        <td>${bmiData[i].bmi}</td>
                        <td>
                            <a data-id="${bmiData[i].objectId}" href="javascript:void(0)">删除</a>
                        </td>
                    </tr>`)
                }
            }
        },
        error(e) {
            loading.style.display = 'none'
            showToast('网络错误，请刷新重试', 3000)
            // console.log(e)
        }
    })
}
// 刷新页面列表初始化
renderList()

tbody.addEventListener('click', function (event) {
    if(event.target.tagName === 'A') {
        let id = event.target.getAttribute('data-id')

        if (confirm('你确定要删除此条数据吗?')) {
            myAjax({
                method: 'DELETE', // get, post, put, delete
                url: 'https://veihwwnelcwq.leanapp.cn/bmi',
                data: {
                    id: id
                },
                success(res) {
                    // console.log(res)
                    renderList()
                }
            })
        }
    }
})

let htaS = document.querySelector('.header_t').querySelectorAll('a')
for (let i = 0; i <= htaS.length - 1; i++) {
    htaS[i].onmousedown = function () {
        this.style.color = 'red'
    }
    htaS[i].onmouseup = function () {
        this.style.color = '#551a8b'
    }
}
let height = document.getElementById('height')
let weight = document.getElementById('weight')
let btn = document.querySelector('button')
let result = document.querySelector('#BMI')
const classify = document.querySelector('#classify')
let img = document.querySelector('#img')
let box = document.querySelector('#box')
const showToast = function (msg, timeout = 1500) {
    let toast = document.createElement('div')
    toast.className = 'toast'
    toast.innerHTML = `<div class="remind">${msg}</div>`
    document.body.prepend(toast)
    setTimeout(function () {
        toast.remove()
    }, timeout)
}

btn.onclick = function () {
    // let BMI = weight.value / ((height.value / 100) ** 2)
    // BMI = BMI.toFixed(1)
    // result.innerHTML = BMI
    if (weight.value ==='' || height.value === '') {
        showToast('请输入合法数据')
    } else {
        // 将当前要计算的数据给到后端，
        // 1. 将身高体重交给后端
        myAjax({
            method: 'POST',
            url: 'https://veihwwnelcwq.leanapp.cn/bmi',
            data: {
                height: height.value,
                weight: weight.value
            },
            success(res) {
                if (res.code === 'ok') {
                    //xhr1.response.data.bmi
                    //xhr1.response.data.status
                    // 2. 改变计算bmi后的样式
                    box.style.display = 'block'
                    img.style.display = 'block'
                    result.innerHTML = res.data.bmi
                    classify.innerHTML = res.data.status
                    if (result.innerHTML >= 28.0) {
                        img.style.top = '146px'
                    } else if (result.innerHTML >= 24.0) {
                        img.style.top = '120px'
                    } else if (result.innerHTML >= 18.5) {
                        img.style.top = '92px'
                    } else if (result.innerHTML <= 18.4 ){
                        img.style.top = '65px'
                    }
                    // 3. 计算后刷新列表
                    renderList()
                } else {
                    //
                }
            },
            error(e) {
                //
            }
        })
    }
}
